import got from "got";
import { createWriteStream } from "fs";
import stream from "stream";
import { promisify } from "util";
import terminalImage from "terminal-image";

import { writeFileByType } from "../../utils/util";
import { randomLenNum } from "../../utils/encryption";

const prefix = process.env.ICAN_IGNORE_DIR
const fileName = prefix + (process.env.ICAN_CODE_FILENAME ?? "code.jpg");

const pipeline = promisify(stream.pipeline);

const randomNum = randomLenNum(4, true)
writeFileByType('code', randomNum)

const url = `http://iep.govmade.com/api/code?randomStr=${randomNum}`;

const downloadStream = got.stream(url);
const fileWriterStream = createWriteStream(fileName);

downloadStream.on("downloadProgress", ({ transferred, total, percent }) => {
  const percentage = Math.round(percent * 100);
  if (transferred > 0) {
    console.error(`progress: ${transferred}/${total} (${percentage}%)`);
  }
});
const downCodeImage = async () => {
  try {
    await pipeline(downloadStream, fileWriterStream);
    console.log(`File downloaded to ${fileName}`);
  } catch (error) {
    console.error(`Something went wrong. ${error.message}`);
  }
};

async function printCode(): Promise<void> {
  await downCodeImage();
  if (fileName) {
    writeFileByType('code', randomNum)
    console.log(await terminalImage.file(fileName));
  }
}

export { downCodeImage, printCode };
